package yxy.game.pm2.module;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.equipdata;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Item;
import yxy.game.pm2.bean.currency.CurrencyType;

public class BlacksmithHandle {

	/** 一键合成 */
	public Collection<Currency> fusionAll(String playerCode, int type, Currency cost) {
		Map<Integer, Currency> equips = Item.all(playerCode, CurrencyType.CT_装备);
		Map<String, equipdata> allData = DataCenter.getAllData(equipdata.class);
		equipdata foreData = null;
		for (equipdata data : allData.values()) {
			if (data.getPosition() != type) {
				continue;
			}
			if (foreData == null) {
				foreData = data;
				continue;
			}
			if (data.level() < foreData.level()) {
				foreData = data;
			}
		}

		EquipTemp temp = mapTemp(equips, allData, foreData);
		temp.merge(cost);

		ArrayList<Currency> result = new ArrayList<>();
		temp.equip(result);

		return result;
	}

	private EquipTemp mapTemp(Map<Integer, Currency> equips, Map<String, equipdata> allData, equipdata data) {
		EquipTemp temp = new EquipTemp();
		temp.data = data;
		if (equips.containsKey(data.getId())) {
			temp.number = equips.get(data.getId()).getNumber();
			temp.orgin = temp.number;
		}
		equipdata nextdata = allData.get(String.valueOf(data.getUpgradeid()));
		if (nextdata != null) {
			temp.next = mapTemp(equips, allData, nextdata);
		}
		return temp;
	}

	private class EquipTemp {
		equipdata data;
		long number;
		long orgin;
		EquipTemp next;

		void merge(Currency cost) {
			if (data.getUpheave() == 1 && next != null) {
				long n = number / data.getHeavenum();
				next.number += n;
				number %= data.getHeavenum();
				cost.setNumber(cost.getNumber() + data.getUpcost() * n);
				next.merge(cost);
			}
		}

		void equip(ArrayList<Currency> list) {
			list.add(Currency.create(CurrencyType.CT_装备, data.getId(), number - orgin));
			if (next != null) {
				next.equip(list);
			}

		}
	}

	/** 有可以合成的装备 */
	public boolean canFusion(String playerCode) {
		Map<Integer, Currency> equips = Item.all(playerCode, CurrencyType.CT_装备);
		for (Currency equip : equips.values()) {
			int dataId = equip.getDataId();
			long number = equip.getNumber();
			equipdata data = DataCenter.getData(dataId, equipdata.class);
			if (data.getUpheave() == 1 && number > data.getHeavenum()) {
				return true;
			}
		}
		return false;
	}

}
